from rest_framework import serializers
from django_redis import get_redis_connection

from goods.models import SKU
from .search_indexes import SKUIndex
from drf_haystack.serializers import HaystackSerializer

class SKUIndexSerializer(HaystackSerializer):
    """
    SKU索引结果数据序列化器
    """
    class Meta:
        index_classes = [SKUIndex]
        fields = ('text', 'id', 'name', 'price', 'default_image_url', 'comments')


class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')


class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')

class UserBrowerHistorySerializer(serializers.Serializer):
    sku_id = serializers.CharField(label='商品id')

    def validate_ske_id(self, value):
        # 校验商品是否存在
        try:
            SKU.objects.get(pk=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError("商品不存在")
        return value

    def create(self, validated_data):
        # 将商品id保存在redis中

        # 获取user信息
        user = self.context['request'].user
        # 获取商品id
        sku_id = validated_data.get('sku_id')
        # 获取redis连接
        redis_conn = get_redis_connection('history')
        # 如果之前保存了,先删除
        redis_conn.lrem('history_%s' % user.id, 0, sku_id)
        # 保存id
        redis_conn.lpush('history_%s' % user.id, sku_id)
        # 限制保存记录数
        redis_conn.ltrim('history_%s' % user.id, 0, 4)
        return validated_data
